<template>
  <el-dialog v-model="visible" title="用户详情" width="600px" :before-close="handleClose" destroy-on-close>
    <div v-if="userStore.loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="userDetail" class="user-detail">
      <!-- 基本信息 -->
      <div class="info-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">用户ID：</span>
              <span class="value">{{ userDetail.id }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">用户名：</span>
              <span class="value">{{ userDetail.username }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 档案信息 -->
      <div class="info-section">
        <h3 class="section-title">档案信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ userDetail.profile?.email || "-" }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">性别：</span>
              <span class="value">{{ userDetail.profile ? getGenderText(userDetail.profile.gender) : "-" }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="info-item">
              <span class="label">地址：</span>
              <span class="value">{{ userDetail.profile?.address || "-" }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="userDetail.profile?.photo" :gutter="20">
          <el-col :span="24">
            <div class="info-item">
              <span class="label">头像：</span>
              <div class="avatar-container">
                <el-avatar :size="80" :src="userDetail.profile.photo" fit="cover">
                  <el-icon><User /></el-icon>
                </el-avatar>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 角色信息 -->
      <div class="info-section">
        <h3 class="section-title">角色信息</h3>
        <div class="info-item">
          <span class="label">分配角色：</span>
          <div class="roles-container">
            <el-tag
              v-for="role in userDetail.roles"
              :key="role.id"
              size="default"
              type="primary"
              style="margin-right: 8px; margin-bottom: 8px; cursor: pointer"
              @click="handleRoleTagClick(role.id)"
            >
              {{ role.name }}
            </el-tag>
            <span v-if="!userDetail.roles?.length" class="value">暂无角色</span>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="no-data">
      <el-empty description="暂无用户详情数据" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑用户</el-button>
      </div>
    </template>
  </el-dialog>
  <ViewRoleDialog v-model="showRoleDialog" :role-id="selectedRoleId" />
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { User } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/user";
import type { User as UserType } from "@/types/user";
import { getGenderText } from "@/types/gender";
import ViewRoleDialog from "../../roles/components/ViewRoleDialog.vue";

defineOptions({
  name: "UserDetailDialog",
});

// Props
interface Props {
  modelValue: boolean;
  userId?: number;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  userId: undefined,
});

// Emits
interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "edit", user: UserType): void;
}

const emit = defineEmits<Emits>();

// Store
const userStore = useUserStore();

// 本地状态
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const userDetail = computed(() => userStore.userDetail);

const selectedRoleId = ref<number | undefined>(undefined);
const showRoleDialog = ref(false);

// 监听对话框打开，加载用户详情
watch(
  () => props.modelValue,
  async (newValue) => {
    if (newValue && props.userId) {
      try {
        await userStore.getUserDetail(props.userId);
      } catch (error) {
        console.error("Failed to load user detail:", error);
      }
    }
  },
  { immediate: true },
);

// 方法
const handleClose = () => {
  visible.value = false;
  // 清理用户详情数据
  userStore.clearUserDetail();
};

const handleEdit = () => {
  if (userDetail.value) {
    emit("edit", userDetail.value);
    handleClose();
  }
};

const handleRoleTagClick = (roleId: number) => {
  selectedRoleId.value = roleId;
  showRoleDialog.value = true;
};
</script>

<style lang="scss" scoped>
.loading-container {
  padding: 20px;
}

.user-detail {
  .info-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      margin: 0 0 16px 0;
      padding-bottom: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
    }

    .info-item {
      margin-bottom: 12px;
      display: flex;
      align-items: flex-start;

      .label {
        min-width: 80px;
        color: #606266;
        font-weight: 500;
        flex-shrink: 0;
      }

      .value {
        color: #303133;
        word-break: break-all;
        flex: 1;
      }

      .avatar-container {
        margin-top: 4px;
      }

      .roles-container {
        flex: 1;
      }
    }
  }
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
